package com.attendance.security;

import com.attendance.security.role.pojo.AbstractRole;
import com.attendance.security.role.service.AbstractRoleService;
import com.attendance.security.user.pojo.UserInfo;
import com.attendance.security.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * UserDetailsService接口实现
 *
 * @author 鵺丶
 * @date 2021/03/08
 */
@Service
public class SecurityUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserService userService;
    @Autowired
    AbstractRoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 通过用户名查找
        UserInfo userInfo = userService.selectByName(username);
        if (userInfo == null) {
            throw new UsernameNotFoundException("未找到该用户");
        }
        //创建List集合，用来保存用户菜单权限，GrantedAuthority对象代表赋予当前用户的权限
        List<GrantedAuthority> authorities = new ArrayList<>();
        //获得当前用户角色集合
        for (AbstractRole role : roleService.getRoleById(userInfo.getUserId())) {
            //将关联对象role的name属性保存为用户的认证权限
            authorities.add(new SimpleGrantedAuthority(role.getRoleCode()));
        }
        //此处返回的是org.springframework.security.core.userdetails.User类，该类是SpringSecurity内部的实现
        //org.springframework.security.core.userdetails.User类实现了UserDetails接口
        return new User(userInfo.getUserName(), userInfo.getPassword(), authorities);
    }
}
